const express = require('express');
const app = express()
const session = require('express-session');
const bodyParser = require('body-parser');
const fs = require('fs');
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');
app.set('views', './views');
// session
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: false
}))

const utils = require('./utils');
let {users} = require('./db/data');
app.use((request,response,next)=>{
    response.locals.uid = request.session.uid ? request.session.uid : null;
    response.locals.username = request.session.username ? request.session.username : null;
    next();
})

app.get('/',(request, response)=>{
    response.render('index');
})

app.get('/login',(request, response)=>{
    response.render('login');
})

app.post('/login',(request, response)=>{
    let password = utils.md5(request.body.password);
    let username = request.body.username;
    console.log(username,password);
    let result = users.find(user=>{
        return user.username == username && user.password == password;
    })
    if(result){
        request.session.username = result.username;
        request.session.uid = result.uid;
    }
    response.redirect('/');
})

app.get('/register', (request, response)=>{
    response.render('register');
})

app.post('/register', (request, response)=>{
    let body = request.body;
    body.uid = utils.nanoid();
    body.password = utils.md5(body.password);
    users.push(body);
    fs.writeFileSync(__dirname + '/db/data.json',JSON.stringify({users}));
    response.redirect('/login');
})

app.get('/logout',(request, response)=>{
    request.session.destroy(()=>{
        response.redirect('/login');
    })
})
app.listen(8080,()=>{
    console.log('server run at 8080!');
})
